import './App.css'
import React from 'react'
import { BrowserRouter,useRoutes } from 'react-router-dom'
import routes from '~react-pages' //引入自动生成的路由列表

const App = () => 
{
    //路由列表
    const Routes = () =>
    {
        //设置全局的跳转路由函数
        React.navigate = useNavigate()

        //设置全局参数接收
        let [searchParams] = useSearchParams()

        //设置全局接收
        React.params = (name: string) => searchParams.get(name ?? '')

        //获取当前访问的路由地址
        const { pathname } = useLocation()
        
        //需要登录的路由判断
        if(!React.RouterRules.includes(pathname)) check()

        return useRoutes(routes)
    }

    //登录判断(路由守卫)
    const check = async () =>
    {
        let id = React.business.id ?? 0
        let mobile = React.business.mobile ?? ''

        //发起请求
        let result = await React.request.post('/business/UserCheck', {id, mobile})

        if(result.code == 0)
        {
            //删除cookie 检查登录失败
            React.business = {}
            React.cookies.remove('business')

            //失败并跳转
            React.toast(result.msg, result.url, 'fail')
            return false
        }

        //覆盖一下cookie信息
        React.business = result.data
        React.cookies.load('business', result.data, {path: '/'})
        return true
    }

    //页面加载中loading...
    const fallback = () => (<React.UI.AutoCenter><React.UI.DotLoading color='primary' /></React.UI.AutoCenter>)

    return (
        <BrowserRouter>
            <React.Suspense fallback={fallback()}>
                <Routes />
            </React.Suspense>
        </BrowserRouter>
    )
}

export default App
